package com.tianya.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianya.domain.dto.CourseOrderRequestDTO;
import com.tianya.domain.entity.Course;
import com.tianya.domain.entity.CourseOrder;
import com.tianya.domain.entity.Parent;
import com.tianya.domain.entity.User;
import com.tianya.domain.enums.PayStatus;
import com.tianya.domain.vo.CourseOrderVO;
import com.tianya.domain.vo.PageResultVO;
import com.tianya.service.CourseOrderService;
import com.tianya.mapper.CourseOrderMapper;
import com.tianya.service.CourseService;
import com.tianya.service.ParentService;
import com.tianya.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder>
        implements CourseOrderService {

    @Resource
    private CourseService courseService;
    @Resource
    private ParentService  parentService;

    @Resource
    private UserService userService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseOrder createCourseOrder(CourseOrderRequestDTO courseOrderRequestDTO) {
        // 构建订单对象
        CourseOrder courseOrder = CourseOrder.builder()
                .parentId(courseOrderRequestDTO.getParentId())
                .courseId(courseOrderRequestDTO.getCourseId())
                .amount(courseOrderRequestDTO.getAmount())
                .status(PayStatus.UNPAID)
                .build();

        // 保存订单
        save(courseOrder);
        return courseOrder;
    }

    @Override
    public PageResultVO<CourseOrderVO> pageCourseOrder(Long pageNum, Long pageSize, CourseOrderRequestDTO courseOrderRequestDTO) {
        // 创建分页对象
        Page<CourseOrder> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        QueryWrapper<CourseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(courseOrderRequestDTO.getCourseId() != null, CourseOrder::getCourseId, courseOrderRequestDTO.getCourseId())
                .eq(courseOrderRequestDTO.getStatus() != null, CourseOrder::getStatus, courseOrderRequestDTO.getStatus())
                .orderByDesc(CourseOrder::getCreatedAt);

        // 执行分页查询
        Page<CourseOrder> courseOrderPage = page(page, queryWrapper);

        List<CourseOrderVO> courseOrderVOList = new ArrayList<>();
        courseOrderPage.getRecords().forEach(courseOrder -> {
            // 获取课程ID
            Long courseId = courseOrder.getCourseId();
            Long parentId = courseOrder.getParentId();

            Course course = courseService.getById(courseId);
            Parent parent = parentService.getById(parentId);
            Long userId = parent!=null?parent.getUserId():null;
            User user = userService.getById(userId);

            CourseOrderVO courseOrderVO = new CourseOrderVO();
            BeanUtil.copyProperties(courseOrder, courseOrderVO);
            courseOrderVO.setCourseName(course!=null?course.getName():"unKnown");
            courseOrderVO.setParentName(parent!=null?user.getName():"unKnown");
            courseOrderVO.setPhone(parent!=null?user.getPhone():"unKnown");
            courseOrderVOList.add(courseOrderVO);
        });
        // 构建返回结果
        return new PageResultVO<>(courseOrderPage.getTotal(),courseOrderVOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(Long orderId, Long parentId) {
        // 构建更新条件
        UpdateWrapper<CourseOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(CourseOrder::getOrderId, orderId)
                .eq(CourseOrder::getParentId, parentId)
                .eq(CourseOrder::getStatus, PayStatus.UNPAID);

        // 更新订单状态为已支付
        CourseOrder updateOrder = new CourseOrder();
        updateOrder.setStatus(PayStatus.PAID);

        return update(updateOrder, updateWrapper);
    }

    @Override
    public CourseOrder getOrderDetail(Long orderId, Long parentId) {
        // 构建查询条件
        QueryWrapper<CourseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(CourseOrder::getOrderId, orderId)
                .eq(CourseOrder::getParentId, parentId);

        return getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(CourseOrderRequestDTO courseOrderRequestDTO) {
        // 验证参数
        if (courseOrderRequestDTO.getId() == null || courseOrderRequestDTO.getParentId() == null) {
            return false;
        }

        // 构建更新条件
        UpdateWrapper<CourseOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(CourseOrder::getOrderId, courseOrderRequestDTO.getId())
                .eq(CourseOrder::getParentId, courseOrderRequestDTO.getParentId())
                .eq(CourseOrder::getStatus, PayStatus.UNPAID); // 只能取消未支付的订单

        // 更新订单状态为已取消
        CourseOrder updateOrder = new CourseOrder();
        updateOrder.setStatus(PayStatus.CANCELED); // 假设3代表已取消状态

        return update(updateOrder, updateWrapper);
    }
}